<template>
  <div>
    <el-upload
      list-type="picture-card"
      action="#"
      :limit="1"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :file-list="fileList"
      :before-upload="beforeUpload"
      :http-request="upload"
      :class="{ disabled: fileComputed, thumbnail: isThumbnail }"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-progress
      v-if="showPercent"
      :percentage="percent"
      style="width: 170px"
    />
    <el-dialog :visible.sync="showDialog">
      <img :src="imgUrl" style="width: 100%" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5' // 引入腾讯云
const cos = new COS({
  SecretId: 'AKIDKUO2PVKtCDxSgeKfla8PQAdplRpwnOhk', // 身份识别 ID
  SecretKey: 'nKaZHjuoWx70c2C5h26vTkkTv61f28xV' // 身份密钥
})

export default {
  props: {
    isThumbnail: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [], // 图片地址设置为数组
      showDialog: false, // 控制显示弹层
      imgUrl: '',
      currentFileUid: '',
      percent: 0,
      showPercent: false
    }
  },
  computed: {
    // 判断是否已经上传完了一张
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  methods: {
    // 预览
    onPreview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    // 移除
    onRemove(file) {
      this.fileList = this.fileList.filter(item => item.uid !== file.uid)
      this.$emit('updata-url', '')
    },
    // 添加文件
    onChange(file, fileList) {
      this.fileList = fileList.map(item => item)
    },
    // 上传之前的动作
    beforeUpload(file) {
      const type = ['image/jpeg', 'image/jpg', 'image/png']
      if (!type.some(item => item === file.type)) {
        this.$message.error('上传图片只能是JPG、JPEG、PNG 格式!')
        return false
      }
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片大小最大不能超过5M')
        return false
      }
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },
    // 自定义上传
    upload(params) {
      if (params.file) {
        // 执行上传操作 上传到cos
        cos.putObject({
          Bucket: 'jlgl-1313037814', /* 填入您自己的存储桶，必须字段 */
          Region: 'ap-guangzhou', /* 存储桶所在地域，例如ap-beijing，必须字段 */
          Key: params.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
          Body: params.file, /* 必须，上传文件对象，可以是input[type="file"]标签选择本地文件后得到的file对象 */
          StorageClass: 'STANDARD',
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          console.log(err || data)
          if (!err && data.statusCode === 200) {
            this.$emit('updata-url', 'http://' + data.Location)
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currentFileUid) {
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
            setTimeout(() => {
              this.showPercent = false
              this.percent = 0
            }, 1000)
          }
        })
      }
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none;
}
.thumbnail .el-upload--picture-card {
  width: 300px !important;
}
.thumbnail .el-upload-list__item {
  width: 300px !important;
}
</style>

